'use client'

import type { AnalysisResult, Layer } from '@shared/schema'
import type { CanvasRef } from '@/components/canvas'
import { Download, FileCode, Image as ImageIcon, Loader2, Settings, Upload as UploadIcon } from 'lucide-react'
import { useRef, useState } from 'react'
import { Canvas } from '@/components/canvas'
import { JsonEditor } from '@/components/json-editor'
import { LayersPanel } from '@/components/layers-panel'
import { PropertiesInspector } from '@/components/properties-inspector'
import { loadSettings, SettingsDialog } from '@/components/settings-dialog'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { UploadZone } from '@/components/upload'

export default function Home() {
  const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null)
  const [selectedLayerId, setSelectedLayerId] = useState<string | null>(null)
  const [isAnalyzing, setIsAnalyzing] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [settingsOpen, setSettingsOpen] = useState(false)
  const [viewMode, setViewMode] = useState<'canvas' | 'json'>('canvas')
  const canvasRef = useRef<CanvasRef>(null)

  // 提取图片区域并去除背景
  const extractImageRegionWithBackgroundRemoval = (
    imageSrc: string,
    x: number,
    y: number,
    width: number,
    height: number,
  ): Promise<string> => {
    return new Promise((resolve) => {
      const img = new Image()
      img.crossOrigin = 'anonymous'
      img.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = width
        canvas.height = height
        const ctx = canvas.getContext('2d', { willReadFrequently: true })
        if (!ctx) {
          resolve('')
          return
        }

        ctx.drawImage(img, x, y, width, height, 0, 0, width, height)

        const imageData = ctx.getImageData(0, 0, width, height)
        const data = imageData.data

        // 采样图片边缘来确定背景色
        const cornerSamples = [
          { x: 0, y: 0 },
          { x: width - 1, y: 0 },
          { x: 0, y: height - 1 },
          { x: width - 1, y: height - 1 },
          { x: Math.floor(width / 2), y: 0 },
          { x: 0, y: Math.floor(height / 2) },
        ]

        let bgR = 0
        let bgG = 0
        let bgB = 0
        cornerSamples.forEach((sample) => {
          const idx = (sample.y * width + sample.x) * 4
          bgR += data[idx]
          bgG += data[idx + 1]
          bgB += data[idx + 2]
        })
        bgR = Math.round(bgR / cornerSamples.length)
        bgG = Math.round(bgG / cornerSamples.length)
        bgB = Math.round(bgB / cornerSamples.length)

        // 移除与背景色相似的像素
        const threshold = 40
        for (let i = 0; i < data.length; i += 4) {
          const r = data[i]
          const g = data[i + 1]
          const b = data[i + 2]

          const distance = Math.sqrt(
            (r - bgR) ** 2 + (g - bgG) ** 2 + (b - bgB) ** 2,
          )

          if (distance < threshold) {
            data[i + 3] = 0
          }
        }

        ctx.putImageData(imageData, 0, 0)
        resolve(canvas.toDataURL('image/png'))
      }
      img.onerror = () => resolve('')
      img.src = imageSrc
    })
  }

  // 获取图层类型名称
  const getLayerTypeName = (type: string) => {
    switch (type) {
      case 'text':
        return '文字'
      case 'shape':
        return '形状'
      case 'image':
        return '图像'
      default:
        return '图层'
    }
  }

  // 处理文件上传
  const handleFileSelect = async (file: File) => {
    setError(null)
    setIsAnalyzing(true)
    setAnalysisResult(null)
    setSelectedLayerId(null)

    try {
      // 将文件转换为 base64
      const reader = new FileReader()
      reader.onload = async (e) => {
        const imageData = e.target?.result as string

        try {
          // 获取图片尺寸
          const img = new Image()
          img.onload = async () => {
            try {
              // 加载设置
              const settings = loadSettings()

              // 调用 API 分析图片
              const response = await fetch('/api/analyze-image', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                  image: imageData,
                  modelName: settings.modelName,
                  prompt: settings.prompt,
                }),
              })

              if (!response.ok) {
                const errorData = await response.json()
                throw new Error(errorData.details || errorData.error || '分析失败')
              }

              const data = await response.json()

              // 提取图片区域（用于 image 类型的 layer）
              const layersWithImages = await Promise.all(
                (data.layers || []).map(async (layer: any) => {
                  if (layer.type === 'image' && layer.position) {
                    // 使用背景去除功能提取图片
                    const extractedImage = await extractImageRegionWithBackgroundRemoval(
                      imageData,
                      layer.position.x,
                      layer.position.y,
                      layer.position.width,
                      layer.position.height,
                    )
                    return {
                      ...layer,
                      imageData: extractedImage,
                      name: layer.content || `图像 ${layer.id}`,
                      visible: true,
                      locked: false,
                      x: layer.position.x,
                      y: layer.position.y,
                      width: layer.position.width,
                      height: layer.position.height,
                    }
                  }

                  // 处理其他类型的 layer
                  return {
                    ...layer,
                    name: layer.content || `${getLayerTypeName(layer.type)} ${layer.id}`,
                    visible: true,
                    locked: false,
                    x: layer.position.x,
                    y: layer.position.y,
                    width: layer.position.width,
                    height: layer.position.height,
                    // 扁平化 style 属性
                    ...(layer.type === 'text' && {
                      fontSize: layer.style?.fontSize ? Number.parseInt(layer.style.fontSize) : 16,
                      fontFamily: layer.style?.fontFamily || 'sans-serif',
                      fontWeight: layer.style?.fontWeight || 'normal',
                      textAlign: layer.style?.textAlign || 'left',
                      color: layer.style?.color || '#000000',
                    }),
                    ...(layer.type === 'shape' && {
                      shapeType: 'rectangle' as const,
                      fill: layer.style?.backgroundColor || '#CCCCCC',
                      stroke: layer.style?.borderColor || '',
                      strokeWidth: layer.style?.borderWidth ? Number.parseInt(layer.style.borderWidth) : 0,
                      cornerRadius: layer.style?.borderRadius ? Number.parseInt(layer.style.borderRadius) : 0,
                    }),
                    ...(layer.type === 'image' && {
                      opacity: layer.style?.opacity ? Number.parseFloat(layer.style.opacity) : 1,
                      description: layer.content,
                    }),
                  }
                }),
              )

              setAnalysisResult({
                imageWidth: img.naturalWidth,
                imageHeight: img.naturalHeight,
                layers: layersWithImages,
                originalImage: imageData,
              })
            }
            catch (err: any) {
              setError(err.message || '分析图片失败')
            }
            finally {
              setIsAnalyzing(false)
            }
          }
          img.onerror = () => {
            setError('加载图片失败')
            setIsAnalyzing(false)
          }
          img.src = imageData
        }
        catch (err: any) {
          setError(err.message || '处理图片失败')
          setIsAnalyzing(false)
        }
      }
      reader.onerror = () => {
        setError('读取文件失败')
        setIsAnalyzing(false)
      }
      reader.readAsDataURL(file)
    }
    catch (err: any) {
      setError(err.message || '上传文件失败')
      setIsAnalyzing(false)
    }
  }

  // 获取选中的图层
  const selectedLayer = analysisResult?.layers.find((l: Layer) => l.id === selectedLayerId)

  // 更新图层
  const handleLayerUpdate = (layerId: string, updates: Partial<Layer>) => {
    if (!analysisResult)
      return

    setAnalysisResult({
      ...analysisResult,
      layers: analysisResult.layers.map((layer: Layer) =>
        layer.id === layerId
          ? {
              ...layer,
              ...updates,
              // 如果更新了 x, y, width, height，也要更新 position
              ...(updates.x !== undefined || updates.y !== undefined || updates.width !== undefined || updates.height !== undefined
                ? {
                    position: {
                      x: updates.x ?? layer.x,
                      y: updates.y ?? layer.y,
                      width: updates.width ?? layer.width,
                      height: updates.height ?? layer.height,
                    },
                  }
                : {}),
            }
          : layer,
      ),
    })
  }

  // 对现有图片图层应用背景去除
  const removeImageBackground = async (layerId: string) => {
    if (!analysisResult)
      return

    const layer = analysisResult.layers.find(l => l.id === layerId)
    if (!layer || layer.type !== 'image' || !layer.imageData)
      return

    try {
      // 从当前图层的 imageData 中去除背景
      const processedImage = await extractImageRegionWithBackgroundRemoval(
        layer.imageData,
        0,
        0,
        layer.width,
        layer.height,
      )

      handleLayerUpdate(layerId, {
        imageData: processedImage,
      })
    }
    catch (err) {
      console.error('背景去除失败:', err)
    }
  }

  // 删除图层
  const handleLayerDelete = (layerId: string) => {
    if (!analysisResult)
      return

    setAnalysisResult({
      ...analysisResult,
      layers: analysisResult.layers.filter((layer: Layer) => layer.id !== layerId),
    })

    if (selectedLayerId === layerId) {
      setSelectedLayerId(null)
    }
  }

  // 重新排序图层
  const handleLayerReorder = (fromIndex: number, toIndex: number) => {
    if (!analysisResult)
      return

    const newLayers = [...analysisResult.layers]
    const [movedLayer] = newLayers.splice(fromIndex, 1)
    newLayers.splice(toIndex, 0, movedLayer)

    setAnalysisResult({
      ...analysisResult,
      layers: newLayers,
    })
  }

  // 导出图片
  const handleExport = async () => {
    if (!analysisResult || !canvasRef.current)
      return

    try {
      const dataURL = await canvasRef.current.getCanvasDataURL()
      if (!dataURL)
        return

      // 将 data URL 转换为 blob 并下载
      const response = await fetch(dataURL)
      const blob = await response.blob()
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `edited-image-${Date.now()}.png`
      a.click()
      URL.revokeObjectURL(url)
    }
    catch (err: any) {
      console.error('导出失败:', err)
      setError('导出图片失败，请重试')
    }
  }

  const handleSettings = () => {
    setSettingsOpen(true)
  }

  // 处理 JSON 编辑器的图层更新
  const handleJsonLayersUpdate = (layers: Layer[]) => {
    if (!analysisResult)
      return

    setAnalysisResult({
      ...analysisResult,
      layers,
    })
  }

  // 切换视图模式
  const toggleViewMode = () => {
    setViewMode(mode => mode === 'canvas' ? 'json' : 'canvas')
  }

  return (
    <main className="flex flex-col h-screen bg-background">
      {/* Top Bar */}
      <header className="h-16 border-b flex items-center justify-between px-4 bg-card">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 rounded-md bg-primary flex items-center justify-center">
            <span className="text-primary-foreground font-semibold text-sm">
              LA
            </span>
          </div>
          <h1 className="text-lg font-semibold">图层分析编辑器</h1>
        </div>
        <div className="flex items-center gap-2">
          {!analysisResult && !isAnalyzing && (
            <>
              <UploadZone onFileSelect={handleFileSelect} />
              <Button variant="outline" size="sm" onClick={handleSettings}><Settings className="w-4 h-4" /></Button>
            </>
          )}
          {analysisResult && (
            <>
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setAnalysisResult(null)
                  setSelectedLayerId(null)
                  setError(null)
                  setViewMode('canvas')
                }}
              >
                <UploadIcon className="w-4 h-4 mr-2" />
                重新上传
              </Button>
              <Button
                variant={viewMode === 'json'
                  ? 'default'
                  : 'outline'}
                size="sm"
                onClick={toggleViewMode}
              >
                {viewMode === 'canvas'
                  ? (
                      <>
                        <FileCode className="w-4 h-4 mr-2" />
                        JSON 视图
                      </>
                    )
                  : (
                      <>
                        <ImageIcon className="w-4 h-4 mr-2" />
                        画布视图
                      </>
                    )}
              </Button>
              <Button variant="outline" size="sm" onClick={handleExport}>
                <Download className="w-4 h-4 mr-2" />
                导出
              </Button>
              <Button variant="outline" size="sm" onClick={handleSettings}><Settings className="w-4 h-4" /></Button>
            </>
          )}
        </div>
      </header>

      <div className="flex-1 flex overflow-hidden">
        {/* 分析中状态 */}
        {isAnalyzing && (
          <div className="flex-1 flex items-center justify-center">
            <div className="text-center space-y-3">
              <Loader2 className="h-12 w-12 animate-spin mx-auto text-primary" />
              <p className="text-lg font-medium">正在分析图片...</p>
              <p className="text-sm text-muted-foreground">请稍候，这可能需要几秒钟</p>
            </div>
          </div>
        )}

        {/* 错误状态 */}
        {error && !isAnalyzing && (
          <div className="flex-1 flex items-center justify-center p-6">
            <Alert variant="destructive" className="max-w-md">
              <AlertDescription>
                <div className="space-y-3">
                  <p className="font-medium">分析失败</p>
                  <p className="text-sm">{error}</p>
                  <Button
                    size="sm"
                    onClick={() => setError(null)}
                  >
                    关闭
                  </Button>
                </div>
              </AlertDescription>
            </Alert>
          </div>
        )}

        {/* 主要内容区 */}
        {analysisResult && !isAnalyzing && (
          <>
            {viewMode === 'canvas'
              ? (
                  <>
                    <div className="flex-1 flex flex-col bg-background min-w-0 overflow-hidden">
                      <Canvas
                        ref={canvasRef}
                        canvasWidth={analysisResult.imageWidth}
                        canvasHeight={analysisResult.imageHeight}
                        layers={analysisResult.layers}
                        selectedLayerId={selectedLayerId}
                        onLayerSelect={setSelectedLayerId}
                        onLayerUpdate={handleLayerUpdate}
                        originalImage={analysisResult.originalImage}
                      />
                    </div>

                    {/* Right Panel */}
                    <div className="w-96 max-w-96 border-l flex flex-col bg-card shrink-0">
                      {/* Layers Panel */}
                      <div className="flex-1 border-b overflow-hidden min-h-0">
                        <LayersPanel
                          layers={analysisResult.layers}
                          selectedLayerId={selectedLayerId}
                          onLayerSelect={setSelectedLayerId}
                          onLayerUpdate={handleLayerUpdate}
                          onLayerDelete={handleLayerDelete}
                          onLayerReorder={handleLayerReorder}
                        />
                      </div>

                      {/* Properties Inspector */}
                      <div className="flex-1 overflow-hidden min-h-0">
                        <PropertiesInspector
                          layer={selectedLayer}
                          onLayerUpdate={(updates) => {
                            if (selectedLayerId) {
                              handleLayerUpdate(selectedLayerId, updates)
                            }
                          }}
                          onRemoveBackground={removeImageBackground}
                        />
                      </div>
                    </div>
                  </>
                )
              : (
                  <div className="flex-1 overflow-hidden">
                    <JsonEditor
                      layers={analysisResult.layers}
                      onLayersUpdate={handleJsonLayersUpdate}
                    />
                  </div>
                )}
          </>
        )}

        {/* 初始空状态 */}
        {!analysisResult && !isAnalyzing && !error && (
          <div className="flex-1 flex items-center justify-center">
            <div className="text-center space-y-6 max-w-md">
              <div className="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center mx-auto">
                <UploadIcon className="w-10 h-10 text-primary" />
              </div>
              <div className="space-y-2">
                <h2 className="text-2xl font-semibold">开始分析图片</h2>
                <p className="text-muted-foreground">
                  上传一张图片，AI 将自动识别其中的文字、形状和图像元素
                </p>
              </div>
              <UploadZone onFileSelect={handleFileSelect} />
            </div>
          </div>
        )}
      </div>

      {/* 设置对话框 */}
      <SettingsDialog open={settingsOpen} onOpenChange={setSettingsOpen} />
    </main>
  )
}
